package com.ipan.jfinal.plugin.userinfo;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 会话-用户信息处理器（自定义）
 * 
 * 注意：mark参数的处理逻辑需要自己实现！
 * 
 * @author iPan
 * @version 2018-04-06
 */
public class SessionUserInfoHandler implements UserInfoHandler {
	
	private static final String USER_KEY = "_login_userinfo"; 
	
	@Override
	public LoginUserInfo getUserInfo(HttpServletRequest httpRequest, String mark) {
		HttpSession session = httpRequest.getSession();
		return (session != null) ? (LoginUserInfo) session.getAttribute(USER_KEY) : null;
	}

	@Override
	public void putUserInfo(HttpServletRequest httpRequest, UserInfo userInfo, String mark) {
		httpRequest.getSession(true).setAttribute(USER_KEY, userInfo);
	}

//	@Override
//	public void putUserInfo(HttpServletRequest httpRequest, Object obj, IConvertUserInfo iConvert) {
//		UserInfo info = (obj instanceof UserInfo) ? (UserInfo)obj : iConvert.convert(obj);
//		putUserInfo(httpRequest, info);
//	}

	@Override
	public void removeUserInfo(HttpServletRequest httpRequest, String mark) {
		HttpSession session = httpRequest.getSession();
		if (session != null) {
			session.removeAttribute(USER_KEY);
		}
	}

	@Override
	public void removeUserInfo(Serializable uuid, String mark) {
		throw new RuntimeException("该方法无法访问"); // 当用户信息存储在servlet以外的地方，需要能够刷新或移除原信息；
	}

	@Override
	public UserInfo getUserInfo(Serializable uuid, String mark) {
		throw new RuntimeException("该方法无法访问");
	}

//	@Override
//	public LoginUserInfo convert(Object obj) {
//		User user = (User) obj;
//		List<String> roles = user.getRoleCodes();
////		UserInfo info = new DefaultUserInfo(user.getId(), user.getUsername(), user.getNickname(), roles);
//		LoginUserInfo info = new LoginUserInfo(user.getId(), user.getUsername(), user.getNickname(), user.getPerId(), user.getPersonName(), roles);
//		return info;
//	}

}
